#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: ck.py
"""
Arquitectura de referencia en commonKads. Vistas.
Este modulo contiene todos los objetos del subsistema Vistas
en la arquitectura MVC (Modelo Vistas Controlador) de la arquitectura
de referencia de CommonKads.
  
"""
__author__ = "Arenas y Jurado"
__date__ = "30 de Agosto 2010"
__version__ = "$Revision: 0.2 - Basado en la version anterior de arhiju $"
__credits__ = """Universidad de Cordoba""" 
from Tkinter import *
from tkFileDialog import *
import Pmw
import ckControlador
import ckModeloAp
import random
import nltk

#import instAplicacion
#==========================================================
#          Variables globales
#============================================================
#classifier=''
#-------------------VISTAS----------------------------------       
#VISTA GENERAL Y MENÚ DE LA APLICACIÓN
#-------------------VISTAS----------------------------------
class App():
    def __init__(self, parent):
         

        parent.title('Sistema de clasificacion de textos')
        self.parent=parent
        # Create the Balloon.
        self.balloon = Pmw.Balloon(parent)
        # Create and pack the MenuBar.
        menuBar = Pmw.MenuBar(parent,
                hull_relief = 'raised',
                hull_borderwidth = 1,
                balloon = self.balloon)
        menuBar.pack(fill = 'x')
        self.menuBar = menuBar
        # Menu de Ver documentos
        menuBar.addmenu('Documentos', 'Presentacion de documentos')
        menuBar.addmenuitem('Documentos', 'command', '',
                command = lambda: ckControlador.event_DocumentsView(parent),
                label = 'Ver documentos de una ontologia')
        menuBar.addmenuitem('Documentos', 'command', '',
                command = lambda: ckControlador.event_DocumentsViewFromCorpus(parent),
                label = 'Ver documentos de un corpus categorizado')        
        menuBar.addmenuitem('Documentos', 'separator')
        menuBar.addmenuitem('Documentos', 'command', 'Salir de la aplicacion',
                command = parent.destroy,
                label = 'Salir')
          
        # Add some buttons to the MenuBar.
        menuBar.addmenu('Clasificacion', 'Clasificacion de documentos')
        menuBar.addmenuitem('Clasificacion', 'command', '',
                command = lambda: ckControlador.event_MachineLearningClassify(parent),
                label = 'Clasificador bayesiano')
        menuBar.addmenuitem('Clasificacion', 'command', '',
                command = lambda: ckControlador.event_MetodoPoda(parent),
                label = 'Clasificacion Automatica Metodo de la poda')
        menuBar.addmenuitem('Clasificacion', 'command', '',
				command = lambda: ckControlador.event_MetodoPodaManual(parent),
				label = 'Clasificacion Manual Metodo de la poda')

        #======================================
        menuBar.addmenu('Evaluacion', 'Evaluacion del reconocimiento')
        menuBar.addmenuitem('Evaluacion', 'command', '',
				command = lambda: ckControlador.event_EvaluarPoda(parent),
				label = 'Evaluación clasificador')
        #======================================
        menuBar.addmenu('Acerca de...', 'Acerca del programa')
        menuBar.addmenuitem('Acerca de...','command','',
                            command= lambda: ckControlador.event_About(parent),
                            label='Acerca de')
#========================================================================
#           CUERPO DE LA APLICACIÓN
#========================================================================
        
        mainPart = Label(parent,
                text = '',
                background = 'gray',
                foreground = 'white',
                padx = 400,
                pady = 260)
        mainPart.pack(fill = 'both', expand = 1)
        self.mainPart=mainPart
#========================================================================
#           BARRA DE MENSAJES
#========================================================================
        messageBar = Pmw.MessageBar(parent,
                entry_width = 40,
                entry_relief='groove',
                labelpos = 'w',
                label_text = 'Status:')
        self.messageBar=messageBar
        self.messageBar.pack(fill = 'x', padx = 10, pady = 10)
        self.messageBar.message('state', 'OK')



    def printAyuda(self):
        print 'ayuda'
        print self.parent
        print self.parent.winfo_id()
        print self.parent.winfo_children()
        for ch in self.parent.winfo_children():
            print ch.winfo_id(), ch.keys(),ch.winfo_name()#,ch.winfo_pathname()
            print
            print ch.winfo_pathname(id=ch.winfo_id())
            print '=================================================='
            print 'ch.winfo_class()',ch.winfo_class(), ch.keys()
            if ch.winfo_class()=='MessageBar':
                print 'estoy en MessageBar'
                print ch.winfo_children()
                print ch, ch.winfo_class()
                #ch.winfo_children()[0].set('asasaasasasasa')
                self.messageBar.message('state', 'OK')
                #ch.message('state', 'OKKKKKKKKKK')
        
         

#-------------------------------------------------------------------------------------
#                VISUALIZACIÓN DE DOCUMENTOS: DIALOGO
#-------------------------------------------------------------------------------
class CDDocumentsView:
    def __init__(self, parent,title):
        self.texto=''
        print 'Estableciendo el cuadro CDDocumentsView'
        #Cuadro de dialogo
        self.dialog = Pmw.Dialog(parent,
            buttons = ('Salir', 'Ayuda'),
            #defaultbutton = 'Fichero',
            title = title,
            hull_height = 400,
            hull_width = 900,
            command = self.execute)
        self.dialog.withdraw()
        #Fichero de ontologias
        #===============================
        self.entryOntoName = Pmw.EntryField(self.dialog.interior(),
		labelpos = 'w',
		label_text = 'Ontologia:',
		validate = None,
                value='../articulos.owl',
                )
        self.entryOntoName.grid(row=0, column=0,sticky=W+E,padx=5, pady=5)
        buttonEntryOntoName = Button(self.dialog.interior(), text = 'Abrir',
                               command = lambda: ckControlador.event_OpenOntologie(ontoName=self.entryOntoName.get(),dW=self.documentList))
        buttonEntryOntoName.grid(row=0, column=1,columnspan=2,sticky=W,padx=5, pady=5)
        #=============================================================================
        #Lista de dDocumentos
        #=====================
        self.documentList = Pmw.ScrolledListBox(self.dialog.interior(),
		items=(''),
		labelpos='nw',
		label_text='Documentos',
		listbox_height = 6,
		selectioncommand=self.selectionCommandDL,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentList.grid(row=1, column=1,columnspan=1,padx=2)

        #Lista de clase de Documentos
        #=====================
        self.documentListClass = Pmw.ScrolledListBox(self.dialog.interior(),
		items=(''),
		labelpos='nw',
		label_text='Clase',
		listbox_height = 6,
		#selectioncommand=self.selectionCommand,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentListClass.grid(row=1, column=2,columnspan=1,padx=2)

        # Texto  a clasificar
        #===============================
        self.historyText = Pmw.HistoryText(self.dialog.interior(),
                text_wrap = 'none',
                text_width = 60,
                text_height = 20,
                #historycommand = self.statechange,
        )
        self.historyText.grid(row=1, column=0,columnspan=1,padx=2)
        self.historyText.component('text').focus()

       #=================================================================================
        self.dialog.activate(geometry = 'centerscreenalways')
        
    #======================================================================================
    # Metodos
    #=======================================================================================
    def execute(self,result):
         
        if result=='Salir':
            print 'Salir'
            self.dialog.deactivate(result)
        if result =='Ayuda':
            pass

    def selectionCommandDL(self):
        print "Elemento seleccionado"
        sels = self.documentList.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels[0]
            self.historyText.clear()
            ckControlador.event_GetBodyTextOntologie(ontoName=self.entryOntoName.get(),
                                       subject=sels[0],
                                       dW=self.historyText)
	    #print self.documentList.index(sels[0])
            #self.documentListClass.select_set(0)
class CDCorpusTrain:
    def __init__(self, parent,title):
        self.texto=''
        print 'CDCorpusTrain'
        #Cuadro de dialogo
        self.dialog = Pmw.Dialog(parent,
            buttons = ('Salir', 'Ayuda'),
            #defaultbutton = 'Fichero',
            title = title,
            hull_height = 400,
            hull_width = 900,
            command = self.execute)
        self.dialog.withdraw()
        #Seleccion Corpus
        #===============================
        self.entryCorpusName = Pmw.EntryField(self.dialog.interior(),
		labelpos = 'w',
		label_text = 'Nombre del Corpus:',
		validate = None,
                value='parrafos_txt',
                )
        self.entryCorpusName.grid(row=0, column=0,columnspan=3,sticky=W+E,padx=5, pady=5)
        #buttonEntryOntoName = Button(self.dialog.interior(), text = 'Abrir',
        #                       command = lambda: ckControlador.event_OpenOntologie(ontoName=self.entryOntoName.get(),dW=self.documentList))
        #buttonEntryOntoName.grid(row=0, column=1,columnspan=2,sticky=W,padx=5, pady=5)
        #=============================================================================
        #Lista de dDocumentos
        #=====================
        self.documentList = Pmw.ScrolledListBox(self.dialog.interior(),
		items=(''),
		labelpos='nw',
		label_text='Documentos',
		listbox_height = 6,
		selectioncommand=self.selectionDoc,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentList.grid(row=1, column=1,columnspan=1,padx=2)

        #Lista de clase de Documentos
        #=====================
        self.documentListClass = Pmw.ScrolledListBox(self.dialog.interior(),
		items=(''),
		labelpos='nw',
		label_text='Clases',
		listbox_height = 6,
		selectioncommand=self.selectionCategory,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentListClass.grid(row=1, column=2,columnspan=1,padx=2)
        #Obtiene las lista de categorias
        categories=ckModeloAp.getCategories()
        print categories
        self.documentListClass.setlist(categories)
        
        # Texto  a clasificar
        #===============================
        self.historyText = Pmw.HistoryText(self.dialog.interior(),
                text_wrap = 'none',
                text_width = 60,
                text_height = 20,
                #historycommand = self.statechange,
        )
        self.historyText.grid(row=1, column=0,columnspan=1,padx=2)
        self.historyText.component('text').focus()

       #=================================================================================
        self.dialog.activate(geometry = 'centerscreenalways')
        
    #======================================================================================
    # Metodos
    #=======================================================================================
    def execute(self,result):
         
        if result=='Salir':
            print 'Salir'
            self.dialog.deactivate(result)
        if result =='Ayuda':
            pass

    def selectionCategory(self):
        print "Elemento seleccionado"
        sels = self.documentListClass.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels
            docList=ckModeloAp.getDocsFromCategories(categories=sels)
            print docList
            self.documentList.setlist(docList)
    def selectionDoc(self):
        print "Elemento seleccionado"
        sels = self.documentList.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels[0]
            text=ckModeloAp.getTextFromDoc(fileids=sels)
            print text
            self.historyText.settext(text)

            
class About:
    def __init__(self, parent):
	# Create dialog.
        Pmw.aboutversion('Clasificacion de Documentos v. 1.0\n'+
                            'Asignatura: Inteligencia Artificial e Ingenieria del Conocimiento\n'+
                            'Prof. Dr. A. Calvo\n'+
                            'ALUMNOS:\n'+
                            'Miguel Ángel Arenas López\n'+
                            'José María Higuera Cerezo\n'+
                            'Maria Isabel Jurado Baena\n'
                         )
        Pmw.aboutcopyright('Copyright Universidad de Cordoba 2010\nAll rights reserved')
        Pmw.aboutcontact(
            'For information about this application contact:\n' +
            '  arhiju'
            )
        self.about = Pmw.AboutDialog(parent, applicationname = 'Clasificacion de textos')
        self.about.withdraw()
    def execute(self):
         self.about.show()




def selectFile(fieldBox=None,destinationWidgwet=None):
    '''Seleccionar un el nombre de un fichero y asignarlo
       a un fieldbox.
'''
    print 'You clicked on', 'de acuerdo', 'Invocar a la tarea',fieldBox['label_text']
    TEXT_FILE_TYPES=[("Ficheros texto","txt")] 
    filePath= askopenfilename(title='Mostrar Fichero',
                              defaultextension='*.txt',
                              filetypes=TEXT_FILE_TYPES,
                              initialdir='')
    #print filePath
    if filePath=='':
        return
    else:
        fieldBox.setvalue(filePath)
    if fieldBox['label_text']=='Fichero de texto:':
        pass
        texto=ckModeloAp.obtenerTextoFichero(filePath)
         
        destinationWidgwet.setvalue(texto)
    
 
class PrintOne:
    def __init__(self, text):
        self.text = text

    def __call__(self):
        print self.text
#=============================================================
#            MARCO PARA REPRESENTAR DOCUMENTOS CATEGORIZADOS
#=============================================================
class FRMCategorizedCorpus:
    def __init__(self, parent,title):
        print 'FRMCategorizedCorpus'
        self.frm = Frame(parent)
        self.frm.pack()
        #Seleccion Corpus
        #===============================
        self.entryCorpusName = Pmw.EntryField(self.frm,
		labelpos = 'w',
		label_text = 'Nombre del Corpus:',
		validate = None,
                value='parrafos_txt',
                )
        self.entryCorpusName.grid(row=0, column=0,columnspan=3,sticky=W+E,padx=5, pady=5)
        #=============================================================================
        #Lista de dDocumentos
        #=====================
        self.documentList = Pmw.ScrolledListBox(self.frm,
		items=(''),
		labelpos='nw',
		label_text='Documentos',
		listbox_height = 6,
		selectioncommand=self.selectionDoc,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentList.grid(row=1, column=2,columnspan=1,padx=2)

        #Lista de clase de Documentos
        #=====================
        self.documentListClass = Pmw.ScrolledListBox(self.frm,
		items=(''),
		labelpos='nw',
		label_text='Clases',
		listbox_height = 6,
		selectioncommand=self.selectionCategory,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentListClass.grid(row=1, column=1,columnspan=1,padx=2)
        #Obtiene las lista de categorias
        categories=ckModeloAp.getCategories()
        print categories
        self.documentListClass.setlist(categories)
        #Lista de palabras mas frecuentes del corpus
        #===========================================
        self.wordListMostFrecuentOfCorpus = Pmw.ScrolledListBox(self.frm,
		items=(''),
		labelpos='nw',
		label_text='Palabras Mas frecuentes',
		listbox_height = 6,
		#selectioncommand=self.selectionCategory,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 160,
		hull_height = 360,
	)
        self.wordListMostFrecuentOfCorpus.grid(row=1, column=3,columnspan=1,padx=2)
        #Obtiene las lista de palabras mas frecuentes
        self.word_features=ckModeloAp.getWordFeatures(corpusName=ckModeloAp.parrafos_txt,nWords=100,tr=0)
        print self.word_features
        self.wordListMostFrecuentOfCorpus.setlist(self.word_features)
        
        
        # Texto  a clasificar
        #===============================
        self.historyText = Pmw.HistoryText(self.frm,
                text_wrap = 'none',
                text_width = 60,
                text_height = 20,
                #historycommand = self.statechange,
        )
        self.historyText.grid(row=1, column=0,columnspan=1,padx=2)
        self.historyText.component('text').focus()

       #=================================================================================
    def selectionCategory(self):
        print "Elemento seleccionado"
        sels = self.documentListClass.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels
            docList=ckModeloAp.getDocsFromCategories(categories=sels)
            print docList
            self.documentList.setlist(docList)
    def selectionDoc(self):
        print "Elemento seleccionado"
        sels = self.documentList.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels[0]
            text=ckModeloAp.getTextFromDoc(fileids=sels)
            print text
            self.historyText.settext(text)
#===========================================================
#     MARCO PARA REPRESENTAR PROPIEDADES DE UN TEXTO
#===========================================================
class FRMTextProperties:
    def __init__(self, parent,frmCorpus):
        self.frmProperties = Frame(parent)
        self.frmProperties.pack()
        #Lista de propiedades del texto
        #==============================
        self.propertiesList = Pmw.ScrolledListBox(self.frmProperties,
		items=(['Propiedades texto']),
		labelpos='nw',
		label_text='Propiedades',
		listbox_height = 6,
		#selectioncommand=self.selectionDoc,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 300,
		hull_height= 200,
	        )
        self.propertiesList.grid(row=0, column=0,rowspan=3,padx=10,sticky=W)
        #Numero de palabras para obtener las propiedades
        #===============================================
        self.entryWordsNumber = Pmw.EntryField(self.frmProperties,
		labelpos = 'n',
		label_text = 'Numero de propiedades',
		validate = {'validator' : 'integer',
			'min' : 1,  'minstrict' : 0},
                value='10',
                )
        self.entryWordsNumber.grid(row=0, column=1,columnspan=1,sticky=NW,padx=10)
        #Porcentaje de muestras de entrenamiento
        #=======================================
        self.entryTrainSetsPercent = Pmw.EntryField(self.frmProperties,
		labelpos = 'n',
		label_text = '% Muestras de entrenamiento',
		validate = {'validator' : 'integer',
			'min' : 1, 'max' : 99, 'minstrict' : 0},
                value='80',
                )
        self.entryTrainSetsPercent.grid(row=1, column=1,columnspan=1,sticky=NW,padx=5)
        #Boton de obtencion de propiedades
        buttonExtratPorperties = Button(self.frmProperties, text = 'Obtener',
        command = lambda: ckControlador.event_ExtractPropertiesFromText(text=frmCorpus.historyText.getvalue(),
                                                                        word_features=frmCorpus.wordListMostFrecuentOfCorpus.get(),
                                                                        dW=self.propertiesList,tr=1))
        buttonExtratPorperties.grid(row=2, column=1,columnspan=3, sticky=W,padx=5,pady=10)

#==============================================================================================
#       Precision del clasificador
        self.entryPrecisionClassifier = Pmw.EntryField(self.frmProperties,
		labelpos = 'n',
		label_text = 'Precision del clasificador',
		validate = {'validator' : 'real',
			'min' : 0.0, 'max' : 100.0, 'minstrict' : 0},
                                                       
                value=''
                )
        self.entryPrecisionClassifier.grid(row=0, column=3,columnspan=1,sticky=NW,padx=10,pady = 10)

#==============================================================================================
#           Resultado de la clasificacion
        self.entryResultClass = Pmw.EntryField(self.frmProperties,
		labelpos = 'n',
		label_text = 'Clase',
		 
                value=''
                )
        self.entryResultClass.grid(row=1, column=3,columnspan=1,sticky=NW,padx=10,pady = 10)

 
        # Create and pack a RadioSelect widget, with radiobuttons.
	#=========================================================
        self.rdbSelectClassifier = Pmw.RadioSelect(self.frmProperties,
		buttontype = 'radiobutton',
		orient = 'vertical',
		labelpos = 'n',
		command = self.callback,
		label_text = 'Seleccion del clasificador',
		hull_borderwidth = 2,
		hull_relief = 'ridge',
	)
        self.rdbSelectClassifier.grid(row=2,column=3, rowspan=2, padx = 10, pady = 10)
#==============================================================================================
	# Add some buttons to the radiobutton RadioSelect.
        for text in ('Clasificador Bayesiano', 'Árboles de decision'):
            self.rdbSelectClassifier.add(text)
        self.rdbSelectClassifier.invoke('Clasificador Bayesiano')
     
    def callback(self, tag):
	# This is called whenever the user clicks on a button
	# in a single select RadioSelect widget.
        print 'Button', tag, 'was pressed.' 
#=================================================================================================
                
#===============================================



#===========================================================
#     MARCO PARA SELECCIONAR CLASIFICADOR ESTADÍSTICO
#===========================================================
class FRMSelectClassifier:
    def __init__(self, parent):
        self.selectClassifier = Frame(parent)
        self.selectClassifier.pack()
	# Create and pack a RadioSelect widget, with radiobuttons.
	#
        rdbSelectClassifier = Pmw.RadioSelect(self.selectClassifier,
		buttontype = 'radiobutton',
		orient = 'vertical',
		labelpos = 'n',
		command = self.callback,
		label_text = 'Seleccion del clasificador',
		hull_borderwidth = 2,
		hull_relief = 'ridge',
	)
        rdbSelectClassifier.grid(row=0,column=0, sticky=NW, padx = 10, pady = 10)

	# Add some buttons to the radiobutton RadioSelect.
        for text in ('Clasificador Bayesiano', 'Árboles de decision'):
            rdbSelectClassifier.add(text)
        rdbSelectClassifier.invoke('Clasificador Bayesiano')
    def callback(self, tag):
	# This is called whenever the user clicks on a button
	# in a single select RadioSelect widget.
        print 'Button', tag, 'was pressed.' 
#===========================================================================================


#======================================================================
#		IMPLEMENTACIÓN CLASIFICADOR BAYESIANO
#======================================================================
class CDCorpusTrainClassify:
    def __init__(self, parent,title):
        self.texto=''
        print 'Clasificador BAYESIANO'
        #Cuadro de dialogo
        self.dialog = Pmw.Dialog(parent,
            buttons = ('Entrenar', 'Clasificar','Salir'),
            #defaultbutton = 'Fichero',
            title = title,
            hull_height = 400,
            hull_width = 900,
            command = self.execute)
        
        self.dialog.withdraw()
        #Seleccion Corpus
        #==========================================================================
        self.corpus=FRMCategorizedCorpus(parent=self.dialog.interior(), title='')
        self.frmTextProperties=FRMTextProperties(parent=self.dialog.interior(),frmCorpus=self.corpus)
        #==========================================================================
        self.dialog.activate(geometry = 'centerscreenalways')
    def execute(self,result):
        global classifier
        if result=='Salir':
            self.dialog.deactivate(result)
        if result =='Clasificar':
            print 'clasificar'
            #Obtenemos el texto
            text=self.corpus.historyText.getvalue()
            #Obtenemos las propiedades del documento
            p=ckModeloAp.document_features(text.split(),self.corpus.word_features)
            #Usamos el clasificador ya entrenado. Hay que asegurarse de que esta entrenado
            print classifier.classify(p)
            self.frmTextProperties.entryResultClass.setvalue(classifier.classify(p))
        if result =='Entrenar':
            #text=self.corpus.historyText.getvalue()
            #print text
            #Obtenemos los datos de los widgets
            nWords=self.frmTextProperties.entryWordsNumber.getvalue()
            print nWords
            cassifierModel=self.frmTextProperties.rdbSelectClassifier.getvalue()
            print cassifierModel
            percentTrain=self.frmTextProperties.entryTrainSetsPercent.getvalue()
            print percentTrain
            #Vamos al controlador
            cl=ckControlador.event_TrainClassifier(corpusName=ckModeloAp.parrafos_txt,
                               nWords=nWords,
                               modelClassify=cassifierModel,
                               percentTrain=percentTrain,
                               tr=True)
            #Podiamos ir directamente al modelo de la aplicacion
            #cl=ckModeloAp.trainClassifier(corpusName=ckModeloAp.parrafos_txt,
            #                   nWords=nWords,
            #                   modelClassify=cassifierModel,
            #                   percentTrain=percentTrain,
            #                   tr=True)
            print cl
            #Actualizamos el clasificador
            classifier=cl[0]
            #Obtenemos la precision
            accuracy=cl[1]
            self.frmTextProperties.entryPrecisionClassifier.setvalue(accuracy)

            pass


#======================================================================
#		IMPLEMENTACIÓN CLASIFICADOR POR MÉTODO DE LA PODA
#======================================================================
class Poda:
    def __init__(self,parent,title):
        self.texto=''
        print 'Clasificador método de la PODA'
        #Cuadro de dialogo
        self.dialog = Pmw.Dialog(parent,
            buttons = ('Clasificar','Salir'),
            title = title,
            hull_height = 400,
            hull_width = 900,
            command = self.execute)
        
        self.dialog.withdraw()
        #Seleccion Corpus
        #==========================================================================
        self.corpus=MarcoSeleccionCorpusPoda(parent=self.dialog.interior(), title='')
        #self.frmTextProperties=FRMTextProperties(parent=self.dialog.interior(),frmCorpus=self.corpus)
        #==========================================================================
        self.dialog.activate(geometry = 'centerscreenalways')
    def execute(self,result):
        global classifier
        if result=='Salir':
            self.dialog.deactivate(result)
        if result =='Clasificar':
            print 'clasificar'
            #Obtenemos el texto
            text=self.corpus.historyText.getvalue()
            #Obtenemos las propiedades del documento
            #p=ckModeloAp.document_features(text.split(),self.corpus.word_features)
            
            categorias = ["ciencias", "letras", "sociales"]
            listaPalabrasCategorizadas = ckModeloAp.getPalabras("palabras.txt")
            #listaPalabrasCategorizadas = [("integral","ciencias"), ("cuerdas","ciencias"), ("aristocracia","letras"), ("Romanticismo","letras"), ("derecho","sociales"), ("emigrantes","sociales")]
            
            #Lĺamo al método de la Poda
            categoria = ckModeloAp.MetodoPoda(text.split(), categorias, listaPalabrasCategorizadas)
            print categoria
            
            self.corpus.entryResultClass.setvalue(categoria)
            #self.frmTextProperties.entryResultClass.setvalue(classifier.classify(p))
            pass


#=============================================================
#**	PODA => MARCO PARA REPRESENTAR DOCUMENTOS CATEGORIZADOS **
#=============================================================
class MarcoSeleccionCorpusPoda:
    def __init__(self, parent,title):
        print 'Marco de selección de Corpus'
        self.frm = Frame(parent)
        self.frm.pack()
        #Seleccion Corpus
        #===============================
        self.entryCorpusName = Pmw.EntryField(self.frm,
		labelpos = 'w',
		label_text = 'Nombre del Corpus:',
		validate = None,
                value='parrafos_txt',
                )
        self.entryCorpusName.grid(row=0, column=0,columnspan=3,sticky=W+E,padx=5, pady=5)
        #=============================================================================
        #Lista de dDocumentos
        #=====================
        self.documentList = Pmw.ScrolledListBox(self.frm,
		items=(''),
		labelpos='nw',
		label_text='Documentos',
		listbox_height = 6,
		selectioncommand=self.selectionDoc,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 150,
		hull_height = 360,
	)
        self.documentList.grid(row=1, column=2,columnspan=1,padx=2)

        #Lista de clase de Documentos
        #=====================
        self.documentListClass = Pmw.ScrolledListBox(self.frm,
		items=(''),
		labelpos='nw',
		label_text='Clases',
		listbox_height = 6,
		selectioncommand=self.selectionCategory,
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 360,
	)
        self.documentListClass.grid(row=1, column=1,columnspan=1,padx=2)
        #Obtiene las lista de categorias
        categories=ckModeloAp.getCategories()
        print categories
        self.documentListClass.setlist(categories)
        
        
        # Texto a clasificar
        #===============================
        self.historyText = Pmw.HistoryText(self.frm,
                text_wrap = 'none',
                text_width = 60,
                text_height = 20,
                #historycommand = self.statechange,
        )
        self.historyText.grid(row=1, column=0,columnspan=1,padx=2)
        self.historyText.component('text').focus()

		# Resultado clasificacion (categoria)
		#===============================
        self.entryResultClass = Pmw.EntryField(self.frm,
            labelpos = 'n',
            label_text = 'Clase', 
            value='')
        self.entryResultClass.grid(row=2, column=0,columnspan=1,sticky=NW,padx=100,pady = 10)
		
       #=================================================================================
    def selectionCategory(self):
        print "Elemento seleccionado"
        sels = self.documentListClass.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels
            docList=ckModeloAp.getDocsFromCategories(categories=sels)
            print docList
            self.documentList.setlist(docList)
    def selectionDoc(self):
        print "Elemento seleccionado"
        sels = self.documentList.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels[0]
            text=ckModeloAp.getTextFromDoc(fileids=sels)
            print text
            self.historyText.settext(text)
            
#==============================================================
# METODO DE CLASIFICACION DE PODA, introduciendo el texto manualmente **
#============================================================== 
class PodaManual:
    def __init__(self,parent,title):
        self.texto=''
        print 'Metodo PODA Manual'
        #Cuadro de dialogo
        self.dialog = Pmw.Dialog(parent,
            buttons = ('Abrir Texto','Clasificar','Salir'),
            title = title,
            hull_height = 400,
            hull_width = 900,
            command = self.execute)
        
        self.dialog.withdraw()
        #==========================================================================
        self.corpus=MarcoSeleccionTexto(parent=self.dialog.interior(), title='')
        #==========================================================================
        self.dialog.activate(geometry = 'centerscreenalways')
    def execute(self,result):
        global classifier
        if result=='Salir':
            self.dialog.deactivate(result)
        if result =='Clasificar':
            print 'clasificar'
            #Obtenemos el texto
            text=self.corpus.historyText.getvalue()
            #Obtenemos las propiedades del documento
            #p=ckModeloAp.document_features(text.split(),self.corpus.word_features)
            
            categorias = ["ciencias", "letras", "sociales"]
            listaPalabrasCategorizadas = ckModeloAp.getPalabras("palabras.txt")
            #listaPalabrasCategorizadas = [("integral","ciencias"), ("cuerdas","ciencias"), ("aristocracia","letras"), ("Romanticismo","letras"), ("derecho","sociales"), ("emigrantes","sociales")]
            
            #Lĺamo al método de la Poda
            categoria = ckModeloAp.MetodoPoda(text.split(), categorias, listaPalabrasCategorizadas)
            print categoria
            
            self.corpus.entryResultClass.setvalue(categoria)
            #self.frmTextProperties.entryResultClass.setvalue(classifier.classify(p))
            pass
        elif result=='Abrir Texto':
			texto = ckModeloAp.AbrirArchivo()
			
			if texto != False:
				self.corpus.historyText.settext(texto)
			
			pass



class MarcoSeleccionTexto:
    def __init__(self, parent,title):
        print 'Marco de selección de Corpus'
        self.frm = Frame(parent)
        self.frm.pack()        
        
        
        # Texto a clasificar
        #===============================
        self.historyText = Pmw.HistoryText(self.frm,
                text_wrap = 'none',
                text_width = 100,
                text_height = 20,
                #historycommand = self.statechange,
        )
        self.historyText.grid(row=1, column=0,columnspan=1,padx=2)
        self.historyText.component('text').focus()

		# Resultado clasificacion (categoria)
		#===============================
        self.entryResultClass = Pmw.EntryField(self.frm,
            labelpos = 'n',
            label_text = 'Clase', 
            value='')
        self.entryResultClass.grid(row=2, column=0,columnspan=1,sticky=NW,padx=300,pady = 10)
		

 
if __name__ == "__main__":
    pass
 

#==============================================================
#**	EVALUADOR => Clasificar todos los textos y mostrar el promedio de aciertos (PODA) **
#==============================================================
class EvaluarPoda:
    def __init__(self,parent,title):
        self.texto=''
        print 'EVALUADOR DEL método de la PODA'
        #Cuadro de dialogo
        self.dialog = Pmw.Dialog(parent,
            buttons = ('Evaluar','Salir'),
            title = title,
            hull_height = 400,
            hull_width = 900,
            command = self.execute)
        
        self.dialog.withdraw()
        #Seleccion Corpus
        #==========================================================================
        self.corpus=MarcoSeleccionEvaluarPoda(parent=self.dialog.interior(), title='')
        #self.frmTextProperties=FRMTextProperties(parent=self.dialog.interior(),frmCorpus=self.corpus)
        #==========================================================================
        self.dialog.activate(geometry = 'centerscreenalways')
        
        
        
    def execute(self,result):
        global classifier
        if result=='Salir':
            self.dialog.deactivate(result)
        if result =='Evaluar':
            print 'Evaluar'         
            # sels clase de articulo seleccionado
            sels = self.corpus.documentListClass.getcurselection() 
            

            
            #imprimir la lista de articulos de la clase seleccionada
            if len(sels) == 0:
                print 'No selection'
            else:
				contadorAciertos = 0			
				contadorAnalizados = 0 

				self.corpus.entryResultClass.setvalue(' ')
				
				print 'Selection:', sels
                #docList, lista de documentos de clase seleccionada
                
				docList=ckModeloAp.getDocsFromCategories(categories=sels)
               
				random.shuffle(docList)
               
                # Tamanio de la lista seleccionada
				size = int (len (docList))

  
				categorias = ["ciencias", "letras", "sociales"]				   
				listaPalabrasCategorizadas = ckModeloAp.getPalabras("palabras.txt")
				
                # imprime la lista de fichero de la categoria
				for i in docList:
				
				   aux = '../../corpus/texto/'+i
				   
				   #abro el texto y guardo en text el contenido
				   text =ckModeloAp.AbrirArchivo(aux)
				   
				   #analizo el texto text
				   categoria = ckModeloAp.MetodoPoda(text.split(), categorias, listaPalabrasCategorizadas)
				   contadorAnalizados +=1

				   PorcentajeAnalizados = (contadorAnalizados * 100)/size
		

                   
				   if categoria[0]==sels[0]:
					   contadorAciertos +=1
					   
				Resultado = (contadorAciertos * 100 )/ size
				print 'Tamanio Lista ' , size
				print 'contadorAciertos ' , contadorAciertos
				print 'Resultado Total ' , Resultado , ' %'	
				self.corpus.entryResultClass.setvalue(str (Resultado) + ' %')
            pass



#=============================================================
#**	EVALUAR PODA => MARCO PARA SELECCION DE CATEGORIA A EVALUAR **
#=============================================================
class MarcoSeleccionEvaluarPoda:
    def __init__(self, parent,title):
        print 'Marco de selección de Corpus'
        self.frm = Frame(parent)
        self.frm.pack()
        
                
        #Seleccion Corpus
        #===============================
        self.entryCorpusName = Pmw.EntryField(self.frm,
		labelpos = 'w',
		label_text = 'Nombre del Corpus:',
		validate = None,
                value='parrafos_txt',
                )
        self.entryCorpusName.grid(row=0, column=0,columnspan=3,sticky=W+E,padx=5, pady=5)        
    
    
        #Numero de Documentos a Evaluar
        #===============================   
        self.entryNumDocs = Pmw.EntryField(self.frm,
		labelpos = 'w',
		label_text = 'Numero de Documentos a evaluar:',
		validate = None,
                value='20',
                )             
        self.entryNumDocs.grid(row=1, column=0,columnspan=3,sticky=W+E,padx=5, pady=5)
        
        #Lista de clase de Documentos
        #=====================
        self.documentListClass = Pmw.ScrolledListBox(self.frm,
		items=(''),
		labelpos='nw',
		label_text='Clases',
		listbox_height = 5,
	
		#dblclickcommand=self.defCmd,
		usehullsize = 1,
		hull_width = 100,
		hull_height = 80,
	)
        self.documentListClass.grid(row=2, column=0,columnspan=10,padx=2)
        #Obtiene las lista de categorias
        categories=ckModeloAp.getCategories()
     #   print categories
        self.documentListClass.setlist(categories)        

  		
		# Resultado Evaluacion (Porcentaje de Aciertos)
		#===============================
        self.entryResultClass = Pmw.EntryField(self.frm,
            labelpos = 'n',
            label_text = 'Porcentaje de Aciertos:', 
            value=' ')
        self.entryResultClass.grid(row=3, column=0,columnspan=1,sticky=NW,padx=100,pady = 10)
        
        
      
		
       #=================================================================================
    def selectionCategory(self):
        print "Elemento seleccionado"
        sels = self.documentListClass.getcurselection()
         
        if len(sels) == 0:
            print 'No selection'
        else:
            print 'Selection:', sels
            docList=ckModeloAp.getDocsFromCategories(categories=sels)

            self.documentList.setlist(docList)
            
            
